import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Pet } from '@/types'
import { petApi } from '@/api/pet'

export const usePetStore = defineStore('pet', () => {
  const pet = ref<Pet | null>(null)
  const loading = ref(false)

  // 获取宠物信息
  const fetchPetInfo = async () => {
    loading.value = true
    try {
      const res = await petApi.getPetInfo()
      if (res.success && res.data) {
        pet.value = res.data
        return true
      }
      return false
    } catch (error) {
      console.error('获取宠物信息失败:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 喂养宠物
  const feedPet = async (foodType: string = 'basic') => {
    loading.value = true
    try {
      const res = await petApi.feedPet(foodType)
      if (res.success && res.data) {
        pet.value = res.data
        return true
      }
      return false
    } catch (error) {
      console.error('喂养宠物失败:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 与宠物玩耍
  const playWithPet = async () => {
    loading.value = true
    try {
      const res = await petApi.playWithPet()
      if (res.success && res.data) {
        pet.value = res.data
        return true
      }
      return false
    } catch (error) {
      console.error('玩耍失败:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 给宠物改名
  const renamePet = async (petName: string) => {
    loading.value = true
    try {
      const res = await petApi.renamePet(petName)
      if (res.success && res.data) {
        pet.value = res.data
        return true
      }
      return false
    } catch (error) {
      console.error('改名失败:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 设置宠物数据
  const setPet = (petData: Pet) => {
    pet.value = petData
  }

  return {
    pet,
    loading,
    fetchPetInfo,
    feedPet,
    playWithPet,
    renamePet,
    setPet
  }
})

